﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Cashier_Service;
using Cashier.utils;
using Cashier_Interface;

namespace Cashier.usercontrols
{
    public partial class TreeViewCategory : UserControl
    {
        private bool showNodeToolTips;
        private GoodsService goodsService;
        private CategoryService categoryService;
        private IReloadData iReloadData;

        [Category("自定义扩展属性")]
        [Description("IReloadData接口实现类")]
        [Browsable(false)]
        public IReloadData IReloadData
        {
            set { iReloadData = value; }
        }

        [Category("自定义扩展属性")]
        [Description("树节是否显示提示信息，默认false")]
        [Browsable(true)]
        public bool ShowNodeToolTips
        {
            get { return showNodeToolTips; }
            set { showNodeToolTips = value; }
        }

        private String nodeValue = String.Empty;

        [Category("自定义扩展属性")]
        [Description("选中节点的值")]
        [Browsable(false)]
        public String NodeValue
        {
            get { return treeView1.SelectedNode != null ? treeView1.SelectedNode.Name : String.Empty; }
        }
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public TreeViewCategory()
        {
            InitializeComponent();
            this.treeView1.BackColor = this.BackColor;
            this.treeView1.HideSelection = false;
            
            this.goodsService = new GoodsService();
            this.categoryService = new CategoryService();

            //自已绘制
            //this.treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
            //this.treeView1.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNode);
        }

        /// <summary>
        /// 初始化控件
        /// </summary>
        public void InitialTreeViewCategory()
        {
            this.InitialTreeView();
        }

        #region  TreeView

        /// <summary>
        /// 初始化类别树
        /// </summary>
        private void InitialTreeView()
        {
            treeView1.ShowNodeToolTips = this.showNodeToolTips;
            TreeNode rootNode = new TreeNode("所有类别");
            rootNode.Name = "0";
            rootNode.Tag = "root";
            treeView1.Nodes.Add(rootNode);

            this.RecursionTreeNodes(rootNode, 0, 1);           
            rootNode.Expand();
            this.SetTreeNodeCategoryCount();
        }

        /// <summary>
        /// 递归初始化树
        /// </summary>
        /// <param name="node"></param>
        /// <param name="parentid"></param>
        /// <param name="depth"></param>
        private void RecursionTreeNodes(TreeNode node, long parentid, int depth)
        {
            try
            {
                DataTable dt = categoryService.GetCategoryTable(0, 0, parentid);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow lopRow in dt.Rows)
                    {
                        long id = (long)lopRow["id"];
                        String name = lopRow["name"].ToString();
                        TreeNode childNode = new TreeNode(name);
                        childNode.Name = id.ToString();
                        childNode.Tag = "0";
                        childNode.ToolTipText = name;
                        node.Nodes.Add(childNode);
                        RecursionTreeNodes(childNode, id, depth + 1);
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 设置分类商品数量
        /// </summary>
        public void SetTreeNodeCategoryCount()
        {
            DataTable dt = goodsService.GetCategoryGroupTable();
            TreeNode rootNode = this.treeView1.Nodes[0];
            GetCategoryCount(rootNode, dt, 1);
        }

        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="dt"></param>
        /// <param name="dept"></param>
        private void GetCategoryCount(TreeNode parentNode, DataTable dt, int dept)
        {
            TreeNodeCollection nodes = parentNode.Nodes;
            if (nodes.Count > 0)
            {
                foreach (TreeNode lopNode in nodes)
                {
                    long category_id = Int64.Parse(lopNode.Name);
                    DataRow[] rows = dt.Select("category_id=" + category_id);
                    if (rows.Length > 0)
                    {
                        String record = rows[0][1].ToString();
                        lopNode.Tag = record;
                        lopNode.Text = rows[0][2].ToString() + "(" + record + ")";
                    }
                    else
                    {
                        lopNode.Tag = "0";
                        lopNode.Text = lopNode.ToolTipText;
                    }
                    if (lopNode.Nodes.Count > 0)
                        GetCategoryCount(lopNode, dt, dept + 1);
                }
            }
        }

        # endregion

        #region 类别树右键菜单事件

        /// <summary>
        /// 新增类别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuItem_treeview_add_Click(object sender, EventArgs e)
        {
            TreeNode selectedNode = treeView1.SelectedNode;
            if (selectedNode != null)
            {
                TreeNode childNode = new TreeNode("新建类别");
                childNode.Name = "0";
                selectedNode.Nodes.Add(childNode);

                if (!selectedNode.IsExpanded)
                    selectedNode.Expand();

                this.treeView1.LabelEdit = true;
                childNode.BeginEdit();
            }
        }

        /// <summary>
        /// 编辑类别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuItem_treeview_edit_Click(object sender, EventArgs e)
        {
            TreeNode selectedNode = treeView1.SelectedNode;
            if (!selectedNode.Name.Equals("0"))
            {
                this.treeView1.LabelEdit = true;
                selectedNode.Text = selectedNode.ToolTipText;
                selectedNode.BeginEdit();
            }
            else
            {
                MessageBox.Show("不可编辑！");
            }
        }

        /// <summary>
        /// 删除类别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuItem_treeview_delete_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode selectedNode = treeView1.SelectedNode;
                if (selectedNode != null)
                {
                    if (selectedNode.Tag.ToString().Equals("root"))
                    {
                        MessageBox.Show("不可删除根类别！");
                        return;
                    }
                    if (selectedNode.Nodes.Count > 0)
                    {
                        MessageBox.Show("含有子类别，不可删除！");
                        return;
                    }
                    else
                    {
                        if ((Int64.Parse(selectedNode.Tag.ToString())) > 0)
                        {
                            MessageBox.Show("分类下存在商品，不可删除！");
                            return;
                        }
                        else
                        {
                            DialogResult result = MessageBox.Show("确定要删除“" + selectedNode.Text + "”类别吗？", "提示", MessageBoxButtons.YesNo);
                            if (result == DialogResult.Yes)
                            {
                                String id = selectedNode.Name;
                                if (Int64.Parse(id) > 0)
                                {
                                    int flag = categoryService.DeleteCategory(id);
                                    if (flag > 0)
                                        selectedNode.Remove();
                                }
                                else
                                    selectedNode.Remove();
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 节点编辑前发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            try
            {
                TreeNode treeNode = e.Node;
                treeNode.Text = treeNode.ToolTipText;
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 编辑完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            try
            {
                TreeNode treeNode = e.Node;
                long categoryid = Int64.Parse(treeNode.Name);

                if (categoryid == 0 && String.IsNullOrEmpty(treeNode.Text))
                {
                    treeNode.Text = "新建类别";
                    treeNode.ToolTipText = treeNode.Text;
                }

                String categoryname = String.IsNullOrEmpty(e.Label) ? treeNode.ToolTipText.Trim() : e.Label.Trim();
                long parentid = Int64.Parse(treeNode.Parent.Name);
                int orderno = 0;
                
                bool exist = categoryService.ExistCategoryName(categoryid, parentid, categoryname);
                if (exist)
                {
                    MessageBox.Show("分类已存在！");
                    e.CancelEdit = true;
                    this.SetTreeNodeCategoryCount();
                    return;
                }

                bool issuccess = false;
                if (categoryid > 0)
                {
                    int flag = categoryService.UpdateCategory(categoryid, categoryname, parentid, orderno);
                    if (flag > 0)
                    {
                        issuccess = true;
                        if (treeNode.Tag != null && Int32.Parse(treeNode.Tag.ToString()) > 0)
                        {
                            treeNode.Text = categoryname + "(" + treeNode.Tag.ToString() + ")";
                        }
                        else
                            treeNode.Text = categoryname;
                        treeNode.ToolTipText = categoryname;
                    }
                }
                else
                {
                    orderno = 1;
                    if (treeNode.PrevNode != null && treeNode.PrevNode != treeNode.Parent)
                        orderno = categoryService.GetCategory(Int64.Parse(treeNode.PrevNode.Name)).Orderno + 1;
                    long id = categoryService.InsertCategory(categoryname, parentid, orderno);
                    if (id > 0)
                    {
                        issuccess = true;
                        treeNode.Name = id.ToString();
                        treeNode.Tag = 0;
                        treeNode.Text = categoryname;
                        treeNode.ToolTipText = categoryname;
                    }
                }

                treeView1.LabelEdit = false;
                if (!issuccess)
                    throw new Exception("编辑商品分类失败：" + categoryname);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }


        /// <summary>
        /// 节点选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag != null && e.Node.Tag.ToString().Equals("root"))
            {
                this.contextMenuItem_treeview_add.Enabled = true;
            }
            else
            {
                this.contextMenuItem_treeview_add.Enabled = false;
            }
            if (iReloadData != null)
            {
                Int64 id = Int64.Parse(e.Node.Name);
                iReloadData.ReloadDataGridViewData(id);
            }
        }

        #endregion

        /// <summary>
        /// 选中树节点
        /// </summary>
        /// <param name="name"></param>
        public void SelectedTreeNode(String name)
        {
            TreeNode selectedNode = this.ReversionTreeNodes(treeView1.Nodes[0], name, 1);          
            treeView1.SelectedNode = selectedNode;
        }

        /// <summary>
        /// 递归节点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="name"></param>
        /// <param name="dept"></param>
        /// <returns></returns>
        private TreeNode ReversionTreeNodes(TreeNode node, String name, int dept)
        {
            TreeNode resultNode = null;
            if (node != null && node.Name.Equals(name))
                resultNode = node;
            else
            {
                TreeNodeCollection nodes = node.Nodes;
                if (nodes != null && nodes.Count > 0)
                {
                    foreach (TreeNode lopNode in nodes)
                    {
                        if (lopNode.Name.Equals(name))
                        {
                            resultNode = lopNode;
                            break;
                        }
                        this.ReversionTreeNodes(lopNode, name, dept + 1);
                    }
                }
            }
            return resultNode;
        }

        //在绘制节点事件中，按自已想的绘制
        private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            //e.DrawDefault = true; //我这里用默认颜色即可，只需要在TreeView失去焦点时选中节点仍然突显
            
            //return;
            
            if ((e.State & TreeNodeStates.Selected) != 0)
            {
                //演示为绿底白字
                //e.Graphics.FillRectangle(Brushes.DarkBlue, e.Node.Bounds);
                
                Font nodeFont = e.Node.NodeFont;
                if (nodeFont == null) nodeFont = ((TreeView)sender).Font;
                //e.Graphics.DrawString(e.Node.Text, nodeFont, Brushes.White, Rectangle.Inflate(e.Bounds, 2, 0));
                e.Graphics.DrawString(e.Node.Text, nodeFont, Brushes.White, e.Node.Bounds.X, e.Node.Bounds.Y+50);
            }
            else
            {
                e.DrawDefault = true;
            }
            /*
            if ((e.State & TreeNodeStates.Focused) != 0)
            {
                using (Pen focusPen = new Pen(Color.White))
                {
                    focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
                    Rectangle focusBounds = e.Node.Bounds;
                    focusBounds.Size = new Size(focusBounds.Width,focusBounds.Height);
                    e.Graphics.DrawRectangle(focusPen, focusBounds);
                }
            }
            */
        }
    }
}
